<?php

namespace app\api\model\service;

use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
class Goods extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'service_goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    /**
     * 获取项目列表
     * @param $param
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function searchGoods($param)
    {
        extract($param);
        $order = 'weigh desc,id desc';
        if (isset($is_rank) && $is_rank != '') {
            $order = $is_rank == 1? 'salenums desc,weigh desc':'salenums asc,weigh desc';
        }
        if (isset($is_price) && $is_rank == '') {
            $order = $is_price == 1? 'price desc,weigh desc':'price asc,weigh desc';
        }
        $newWhere= "status='normal' AND shop_state=1 AND deletetime IS NULL";
        if (isset($name) && $name != '') {
            $newWhere.= " AND name LIKE '%{$name}%'";
        }

        if(isset($goods_id))
        {
            $newWhere.= " AND id={$goods_id}";
        }
        if(isset($category_id) && $category_id != '')
        {
            $newWhere.= " AND category_id={$category_id}";
        }
        if(isset($is_seckill) && $is_seckill != '')
        {
            $newWhere.= " AND is_seckill={$is_seckill}";
        }
        if(isset($is_hot) && $is_hot != '')
        {
            $newWhere.= " AND is_hot={$is_hot}";
        }else{
            $newWhere.= " AND is_show=1";
        }
        if(isset($is_home_hot) && $is_home_hot != '')
        {
            $newWhere.= " AND is_home_hot={$is_home_hot}";
        }
        if(isset($two_category_id) && $two_category_id != '')
        {
            $newWhere.= " AND two_category_id={$two_category_id}";
        }
        if(isset($category_ids) && $category_ids != '')
        {
            $categoryIdsArray = explode(',', $category_ids);
            $newWhere.= " AND category_id IN {$categoryIdsArray}";
            $newWhere.= " AND shop_id=0";
        }
        if(isset($shop_id) && $shop_id != '')
        {
            $newWhere.= " AND shop_id={$shop_id}";
        }
        if(isset($city) && $city != '')
        {
            $newWhere.= " AND (city='{$city}' OR city IS NULL)";
        }
        if(isset($skill_cate_id) && $skill_cate_id != '')
        {
            $newWhere.= " AND FIND_IN_SET('$skill_cate_id',skill_cate_ids)";
        }
        if (isset($goods_ids) && $goods_ids != '') {
            $newWhere.= " AND id IN ({$goods_ids})";
        }
        if(isset($two_category_id) && $two_category_id != '')
        {
            $newWhere.= " AND two_category_id={$two_category_id}";
        }
        $limit = $limit?:10;
        $page = empty($page)?0:($page-1)*$limit;
        $limit = $page.','.$limit;
        $config = config('database');
        $db = $config['prefix'].'service_goods';
        $list = Db::query("SELECT id,name,image,type,skill_cate_ids,price,original_price,
                    response_hour,shop_id,tag_name,cost_seconds,salenums 
                FROM {$db} WHERE $newWhere ORDER BY {$order} LIMIT {$limit}");
        return $list;
    }

    public static function getNewShopGoods($ids,$type=0)
    {
        if(!$ids)
        {
            return '';
        }
        $idArr = explode(',',$ids);
        $list = [];
        $i = 0;
        foreach ($idArr as $val)
        {
            if($i>=2 && $type == 0)
            {
                break;
            }
            $goods = self::where(['id'=>$val,'status'=>'normal','shop_state'=>1])->field('id,name,image,type,skill_cate_ids,price,response_hour,shop_id,tag_name,cost_seconds,salenums')->find();
            if($goods)
            {
                $list[] = $goods;
                $i++;
            }
        }
        return $list;
    }





    /**
     * 添加商品
     * @param $post
     * @return true
     * @throws Exception
     */
    public static function addGoods($post)
    {
        $goods = new Goods($post);
        $goods->allowField(true)->save();

        if($post['spec_type'] == 1) {
            $spuList = json_decode($post['spu'], true);
            $spu = [];
            foreach ($spuList as $value) {

                $spu[] = [
                    'goods_id' => $goods->id,
                    'name' => $value['name'],
                    'skudetail' => implode(',', array_column($value['info'], 'name'))
                ];
            }
            if (!model('\app\api\model\service\GoodsSpu')->allowField(true)->saveAll($spu)) {
                throw new Exception('添加规格失败');
            }
            $skuList = json_decode($post['sku'], true);
            $sku = [];
            foreach ($skuList as $value) {

                $sku[] = [
                    'goods_id' => $goods->id,
                    'name' => $value['name'],
                    'price' => $value['price'],
                    'cost_seconds'=>$value['cost_seconds']
                ];
            }
            if (!model('\app\api\model\service\GoodsSku')->allowField(true)->saveAll($sku)) {
                throw new Exception('添加规格详情失败');
            }
        }
        if(isset($post['addGoods']))
        {
            $goodsAdd = [];
            $addGoodsList = json_decode($post['addGoods'], true);
            foreach ($addGoodsList as $value)
            {
                $goodsAdd[] = [
                    'goods_id' => $goods->id,
                    'name' => $value['name'],
                    'price' => $value['price'],
                    'cost_seconds' => $value['cost_seconds']
                ];
            }
            if (!model('\app\api\model\service\GoodsAdd')->allowField(true)->saveAll($goodsAdd)) {
                throw new Exception('添加附加项目失败');
            }
        }
        return true;
    }


    public static function editGoods($post)
    {
        $post['shop_state'] = 0;
        $goods = new \app\api\model\service\Goods ();
        $spec_type =  self::where(['id'=>$post['id']])->value('spec_type');
        $goods->allowField(true)->save($post,['id'=>$post['id']]);
        if($post['spec_type'] == 1) {
            $spuList = json_decode($post['spu'], true);
            $spu = [];
            foreach ($spuList as $value) {

                $spu[] = [
                    'goods_id' => $goods->id,
                    'name' => $value['name'],
                    'skudetail' => implode(',', array_column($value['info'], 'name'))
                ];
            }
            if($spec_type == 1)
            {
                $goodsSpu = new GoodsSpu();
                $goodsSpu->save(['status'=>'hidden'],['goods_id' => $post['id'],'status'=>'normal']);
                $goodsSku = new GoodsSku();
                $goodsSku->save(['status'=>'hidden'],['goods_id' => $post['id'],'status'=>'normal']);
            }
            if (!model('\app\api\model\service\GoodsSpu')->allowField(true)->saveAll($spu)) {
                throw new Exception('添加规格失败');
            }
            $skuList = json_decode($post['sku'], true);
            $sku = [];
            foreach ($skuList as $value) {

                $sku[] = [
                    'goods_id' => $goods->id,
                    'name' => $value['name'],
                    'price' => $value['price'],
                    'cost_seconds' => $value['cost_seconds']
                ];
            }
            if (!model('\app\api\model\service\GoodsSku')->allowField(true)->saveAll($sku)) {
                throw new Exception('添加规格详情失败');
            }
        }
        if(isset($post['addGoods']))
        {
            $goodsAdd = [];
            $addGoodsList = json_decode($post['addGoods'], true);
            foreach ($addGoodsList as $value)
            {
                $goodsAdd[] = [
                    'goods_id' => $goods->id,
                    'name' => $value['name'],
                    'price' => $value['price'],
                    'cost_seconds' => $value['cost_seconds']
                ];
            }
            $goodsSku = new GoodsAdd();
            $goodsSku->save(['state'=>0],['goods_id' => $post['id'],'state'=>1]);
            if (!model('\app\api\model\service\GoodsAdd')->allowField(true)->saveAll($goodsAdd)) {
                throw new Exception('添加附加项目失败');
            }
        }
        return true;
    }

    public static function getSkillGoods($ids)
    {
        if(!$ids)
        {
            return '';
        }
        $idArr = explode(',',$ids);
        $list = [];
        foreach ($idArr as $val)
        {
            $goods = self::where(['id'=>$val,'status'=>'normal','shop_state'=>1])->field('id,name,shop_id,image,price,tag_name,response_hour,salenums,type')->find();
            if($goods)
            {
                $goods['shopName'] = $goods['shop_id']?Shop::getName($goods['shop_id']):'';
                $list[] = $goods;
            }
        }
        return $list;
    }

    public static function getShopPlatformGoods($ids,$shopUid)
    {
        $shopId = Shop::where(['user_id'=>$shopUid])->value('id');
        if(!$ids || !$shopId)
        {
            return '';
        }
        $shopGoodsList = self::where(['shop_id'=>$shopId])->column('id');
        $idArr = explode(',',$ids);
        $list = [];
        foreach ($idArr as $val)
        {
            $goods = !in_array($val,$shopGoodsList) ? self::where(['id'=>$val,'status'=>'normal','shop_state'=>1])->field('id,name,shop_id,image,price,tag_name,response_hour,salenums,type')->find() :'';
            if($goods)
            {
                $goods['shopName'] = $goods['shop_id']?Shop::getName($goods['shop_id']):'';
                $list[] = $goods;
            }
        }
        return $list;
    }



    /**
     * 项目下架
     * @param $id
     * @return Goods
     */
    public static function downGoods($id)
    {
        return self::where(['id'=>$id])->update(['status'=>'hidden']);
    }


    /**
     * 项目下架
     * @param $id
     * @return Goods
     */
    public static function upGoods($id)
    {
        return self::where(['id'=>$id])->update(['status'=>'normal']);
    }

    /**
     * 获取商品详情
     * @param $id
     * @param $uid
     * @return array|bool|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getInfo($id,$uid='')
    {
        $where['id'] = $id;

        $info = self::where($where)->field('id,name,cost_seconds,image,price,cost_seconds,response_hour,shop_id,tag_name,to_shop,salenums,images,spec_type,choose_skill_type,flow_path_images,illustrate_images')->find();

        if(!$info)
        {
            return false;
        }
        $info['images'] = explode(',',$info['images']);
        $info['shopname'] = $info['shop_id']?Shop::getName($info['shop_id']):'';
        $info['flow_path_images'] = explode(',',$info['flow_path_images']);
        $info['illustrate_images'] = explode(',',$info['illustrate_images']);
        $info['followState'] = $uid ? Follow::getState(['follow_id'=>$id,'user_id'=>$uid,'type'=>1],1):0;
        $info['spu'] = $info['spec_type'] == 1?GoodsSpu::getSpuList($info['id']):[];
        $info['sku'] = $info['spec_type'] == 1?GoodsSku::getSkuList($info['id']):[];

        //购买须知 & 购后须知
        $purchase_info_lists = Db::name("service_project_config")->field("purchase_info_ids, after_purchase_info_ids")->find();

        $info["purchase_info_detail"] = [];
        $info["after_purchase_info_detail"] = [];
        if(!empty($purchase_info_lists["purchase_info_ids"])){
            //对应id查询详情
            $purchase_info_ids_lists = Db::name("service_config_text")
            ->field("id, name as title, content")
            ->where("id in (" . $purchase_info_lists["purchase_info_ids"] . ")")
            ->order("sort desc")
            ->select();

            if($purchase_info_ids_lists){
                $info["purchase_info_detail"] = $purchase_info_ids_lists;
            }

        }
        if(!empty($purchase_info_lists["after_purchase_info_ids"])){
            //对应id查询详情
            $after_purchase_info_ids_lists = Db::name("service_config_text")
            ->field("id, name as title, content")
            ->where("id in (" . $purchase_info_lists["after_purchase_info_ids"] . ")")
            ->order("sort desc")
            ->select();

            if($after_purchase_info_ids_lists){
                $info["after_purchase_info_detail"] = $after_purchase_info_ids_lists;
            }
        }
        return $info;
    }

    public static function getShopGoods($id)
    {
        $where = [
            'id' => $id,
            'status'=>'normal'
        ];
        $use = ['goods_id'=>$id];
        $goods = self::where(['id'=>$id])->find();
        if($goods['spec_type'] == 1)
        {
            $goods = self::where($where)->with(['spu' => function($query) use ($use) {
                $query->where(['goods_id'=>$use['goods_id'],'status'=>'normal']);
            },'sku' => function($query) use ($use) {
                $query->where(['goods_id'=>$use['goods_id'],'status'=>'normal']);
            }])->order('weigh desc')->find();
        }
        $goods['addGoods'] = GoodsAdd::getList($id);
        $goods['category_name'] = Category::getName($goods['category_id']);
        $goods['two_category_name'] = Category::getName($goods['two_category_id']);
        $goods['skill_cate_name_list'] = SkillCate::getNameList($goods['skill_cate_ids']);
        return $goods;
    }

    public static function getCount($params)
    {
        $params['status'] = 'normal';
        return self::where($params)->count();
    }

    public static function getName($id)
    {
        return self::where('id',$id)->value('name');
    }


    public function spu()
    {
        return $this->hasMany('GoodsSpu','goods_id');
    }

    public function sku()
    {
        return $this->hasMany('GoodsSku','goods_id');
    }




}
